import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { ExwarehousmanageService } from '../../xstorage-manage-services/exwarehous-manage.service';

@Component({
  selector: 'app-storage-exwarehous-details',
  templateUrl: './storage-exwarehous-details.component.html',
  styleUrls: ['./storage-exwarehous-details.component.scss']
})
export class StorageExwarehousDetailsComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {};

  formParams: any = {
    type: '', // 出库类型
    whId: '', // 出库仓库
    quality: '', // 出库品质
    arrivalTime: '', // 预计到货日期
    contractEnclosure: '', // 附件
    remark: '', // 备注
    supId: '', // 供应商
    consignee: '', // 收货人
    tel: '', // 联系方式
    address: '', // 地址
    deliveryMethod: '', // 配送方式
    isFreight: '' // 邮费承担
  };

  exwarehousTableData: any[] = [];

  outTypeOptions: any[] = []; // 出库类型Options
  supplierOptions: any[] = []; // 供应商Options
  warehouseOptions: any[] = []; // 仓库Options
  locationOptions: any[] = []; // 库位Options
  logisticsOptions: any[] = []; // 物流Options

  /**
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  isZfVisible = false;
  submitZfLoading = false;
  toVoidItem: any = {};
  toVoidRemark = ''; // 作废备注

  /**
   * SN 信息 Modal
   * ----------------------------------------------------------------
   */
  isSninfoVisible = false;
  snModalTable: any[] = [];

  /**
   * 多库位 信息 Modal
   * ----------------------------------------------------------------
   */
  isDkwVisible = false;
  locationModalTable: any[] = [];

  /**
   * 仓库修改 Modal
   * ----------------------------------------------------------------
   */
  isStoreVisible = false;
  storeParams = {
    whId: ''
  };
  modifyStoreLoading = false;

  /**
   * 收获人信息修改 Modal
   * ----------------------------------------------------------------
   */
  isReceVisible = false;
  modifyReceLoading = false;
  validateReceForm!: FormGroup;

  /**
   * 配送方式修改 Modal
   * ----------------------------------------------------------------
   */
  isDeliveryVisible = false;
  modifyDeliveryLoading = false;
  deliveryOptions: any[] = [...storageDeliveryMethodArrs];
  validateDeliveryForm!: FormGroup;

  /**
   * 商品明细 table check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => item.lineState === 0);
    listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => item.lineState === 0);
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private fb: FormBuilder,
    private commonService: CommonService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: ExwarehousmanageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadOutTypeOptions();
    this.loadSupplierList();
    this.loadWarehouseList();
    this.loadLogisticsData();
    this.loadLocationOptions();

    this.loadDetailData();

    this.validateReceForm = this.fb.group({
      supId: [''], // 供应商
      consignee: ['', [Validators.required]], // 收货人
      tel: ['', [Validators.required]], // 联系方式
      address: ['', [Validators.required]] // 详细地址
    });

    this.validateDeliveryForm = this.fb.group({
      isFreight: ['', [Validators.required]], // 运费承担
      deliveryMethod: ['', [Validators.required]], // 配送方式
      expressCode: [''], // 物流公司
      expressNo: [''], // 物流单号
      expressPrice: [''] // 运费
    });
  }

  // 出库类型options
  async loadOutTypeOptions() {
    const res: any = await this.commonService.getDictList('outbound_type');
    this.outTypeOptions = res || [];
  }

  // 查询物流
  async loadLogisticsData() {
    const res: any = await this.commonService.getDictList('logistics_company');
    this.logisticsOptions = (res && res.length) ? res : [];
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
  }

  // 查询仓库
  async loadWarehouseList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data?.records.filter((item: any) => [1].includes(item.state));
    } else {
      this.msg.error(message);
    }
  }

  // 查询库位Options
  async loadLocationOptions() {
    let params = {
      // whId: !this.commonService.isEmpty(this.routeParams.whId) ? this.routeParams.whId : '',
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getLocationList(params);
    if (code === 0) {
      this.locationOptions = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  async loadDetailData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data}: any = await this.services.getExwarehousDetailData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const { delivery, list } = data || {};

      this.detailsData = delivery || {};
      this.detailsData.fileList = delivery.contractEnclosure ? this.handleList(delivery.contractEnclosure.split(',')) : [];
      this.exwarehousTableData = list || [];

      for (let key in this.formParams) {
        this.formParams[key] = delivery[key] || '';
      }
    }
  }

  /**
   * 作废
   * ----------------------------------------------------------------
   */
  showTovoidModal(item: any) {
    this.toVoidItem = item;
    this.toVoidRemark = '';

    if (!this.commonService.isEmpty(item.actualNumber) && item.actualNumber !== 0) {
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: '该行明细已有出库数量，建议提前核实，确认作废吗？',
        nzOkText: '确定',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.isZfVisible = true;
        },
        nzCancelText: '取消'
      });
    } else {
      this.isZfVisible = true;
    }
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      id: this.toVoidItem.id,
      state: 1, // 状态 0正常 1已作废
      note: this.toVoidRemark
    }
    this.submitZfLoading = true;
    const {code, message}: any = await this.services.tovoidExwarehousData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.msg.success('操作成功');
      this.loadDetailData();
    }
  }

  /**
   * SN 信息
   * ----------------------------------------------------------------
   */
  showSnInfosModal(item: any) {
    this.snModalTable = !this.commonService.isEmpty(item.itemSns) ? JSON.parse(item.itemSns) : [];
    this.isSninfoVisible = true;
  }

  /**
   * 多库位 信息
   * ----------------------------------------------------------------
   */
  showLocationModal(item: any) {
    this.locationModalTable = !this.commonService.isEmpty(item.libraryText) ? JSON.parse(item.libraryText) : [];
    this.isDkwVisible = true;
  }

  /**
   * 修改仓库 Modal
   * ----------------------------------------------------------------
   */
  showEditStoreModal() {
    this.storeParams.whId = '';
    this.isStoreVisible = true;
  }

  async subModifyStore() {
    if (this.commonService.isEmpty(this.storeParams.whId)) {
      this.msg.warning('请选择新仓库');
      return
    }

    let params = {
      updateType: 2, // 1 修改配送信息 2 修改仓库 3 修改收货人信息 4 取消物流单
      delivery: {
        id: this.routeParams.id,
        whId: this.storeParams.whId
      }
    }
    this.modifyStoreLoading = true;
    const {code, message}: any = await this.services.updateDeliveryOrderInfoData(params);
    this.modifyStoreLoading = false;

    if (code === 0) {
      this.isStoreVisible = false;
      this.loadDetailData();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 收获人信息修改 Modal
   * ----------------------------------------------------------------
   */
  showEditReceModal() {
    // 如果配送方式 = 物流(系统自动下单)，并且物流单号不为空
    if (this.detailsData.deliveryMethod === 1 && !this.commonService.isEmpty(this.detailsData.expressNo)) {
      this.msg.warning('请先取消已经上传的物流单信息');
      return
    }
    
    this.validateReceForm.reset();
    this.validateReceForm.patchValue({
      supId: !this.commonService.isEmpty(this.detailsData.supId) ? Number(this.detailsData.supId) : '', // 供应商
      consignee: this.detailsData.consignee || '', // 收货人
      tel: this.detailsData.tel || '', // 联系方式
      address: this.detailsData.address || '' // 详细地址
    })
    this.isReceVisible = true;
  }

  async subEditReceData() {
    if (this.validateReceForm.valid) {
      let params = {
        updateType: 3, // 1 修改配送信息 2 修改仓库 3 修改收货人信息 4 取消物流单
        delivery: {
          id: this.routeParams.id,
          ...this.validateReceForm.value
        }
      }
      for (let key in params.delivery) {
        if (this.commonService.isEmpty(params.delivery[key])) {
          params.delivery[key] = '';
        }
      }
      
      // return
      this.modifyReceLoading = true;
      const {code, message}: any = await this.services.updateDeliveryOrderInfoData(params);
      this.modifyReceLoading = false;
  
      if (code === 0) {
        this.isReceVisible = false;
        this.loadDetailData();
      } else {
        this.msg.error(message);
      }
    } else {
      Object.values(this.validateReceForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 修改配送方式 Modal
   * ----------------------------------------------------------------
   */
  showEditDeliveryModal() {
    // 如果配送方式 = 系统自动下单，并且物流单号不为空
    if (this.detailsData.deliveryMethod === 1 && !this.commonService.isEmpty(this.detailsData.expressNo)) {
      this.msg.warning('请先取消物流单');
      return
    }
    this.validateDeliveryForm.reset();

    this.validateDeliveryForm.patchValue({
      isFreight: this.detailsData.isFreight, // 运费承担
      deliveryMethod: this.detailsData.deliveryMethod, // 配送方式
      expressCode: this.detailsData.expressCode, // 物流公司code
      expressNo: this.detailsData.expressNo, // 物流单号
      expressPrice: this.detailsData.expressPrice || '' // 运费
    })
    
    this.deliveryChange(this.detailsData.deliveryMethod);
    this.isDeliveryVisible = true;
  }

  deliveryChange(val: any) {
    this.validateDeliveryForm.get('expressCode')?.setValue('');
    
    // (系统下单 | 手动下单), 物流公司 必填
    if ([1, 2].includes(val)) {
      this.validateDeliveryForm.get('expressCode')!.setValidators(Validators.required);
      this.validateDeliveryForm.get('expressCode')!.markAsDirty();
    } else {
      this.validateDeliveryForm.get('expressCode')!.clearValidators();
      this.validateDeliveryForm.get('expressCode')!.markAsPristine();
    }

    // 手动下单，物流单号 必填
    if (val === 2) {
      this.validateDeliveryForm.get('expressNo')!.setValidators(Validators.required);
      this.validateDeliveryForm.get('expressNo')!.markAsDirty();
    } else {
      this.validateDeliveryForm.get('expressNo')!.clearValidators();
      this.validateDeliveryForm.get('expressNo')!.markAsPristine();
    }

    ['expressCode', 'expressNo'].forEach(key => {
      this.validateDeliveryForm.get(key)!.updateValueAndValidity();
    })

    // 系统下单, 物流单号 & 运费 清空
    if (val === 1) {
      this.validateDeliveryForm.patchValue({
        expressNo: '',
        expressPrice: ''
      });
    }

    // 线下配送, 物流公司 & 物流单号 清空
    if (val === 3) {
      this.validateDeliveryForm.patchValue({
        expressCode: '',
        expressNo: ''
      });
    }

    // (动态设置)物流单号Input设置禁用
    if ([1, 3].includes(val)) {
      this.validateDeliveryForm.controls.expressNo.disable();
    } else {
      this.validateDeliveryForm.controls.expressNo.enable();
    }
  }

  async subEditDeliveryData() {
    if (this.validateDeliveryForm.valid) {
      let logisticsObj = this.logisticsOptions.find(ele => ele.content == this.validateDeliveryForm.value.expressCode);
      let params = {
        updateType: 1, // 1 修改配送信息 2 修改仓库 3 修改收货人信息 4 取消物流单
        delivery: {
          id: this.routeParams.id,
          ...this.validateDeliveryForm.value,
          expressName: logisticsObj?.name || '', // 物流公司名
          expressNo: this.validateDeliveryForm.value.expressNo || '' // 物流单号
        }
      }
      // return
      this.modifyDeliveryLoading = true;
      const {code, message}: any = await this.services.updateDeliveryOrderInfoData(params);
      this.modifyDeliveryLoading = false;
  
      if (code === 0) {
        this.isDeliveryVisible = false;
        this.loadDetailData();
      } else {
        this.msg.error(message);
      }
    } else {
      Object.values(this.validateDeliveryForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 取消物流单
   */
  cancelLogisticsBill() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认取消已经上传的单据信息?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          id: this.routeParams.id
        }
        const {code, message}: any = await this.services.cancelLogisticsOrderData(params);
        if (code === 0) {
          this.msg.success('物流单取消成功');
          this.loadDetailData();
        } else {
          this.msg.error(message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * 拆单
   * ----------------------------------------------------------------
   */
  verifSplitOrderData() {
    if (!this.commonService.isEmpty(this.detailsData.expressNo)) {
      this.msg.warning('该出库单已经有物流单号，无法继续拆单，您可以先修改/取消物流单以后再试');
      return false;
    } else if (!this.setOfCheckedId.size) {
      this.msg.warning('请先勾选需要拆分发货的商品');
      return false;
    } else {
      return true;
    }
  }

  subSplitOrder() {
    if (!this.verifSplitOrderData()) {
      return
    }

    let selectIds = [...this.setOfCheckedId];
    let arrs = this.exwarehousTableData.filter(ele => selectIds.includes(ele.id));

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认拆单吗?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params: any = {
          isSplit: 1, // 0：添加、1：拆单
          delivery: {
            id: this.routeParams.id,
            oldDeliveryNumber: this.detailsData.deliveryNumber, // 旧单号(后端用)
            createTime: this.detailsData.createTime || '', // 新建时间(后端用)
            founder: this.detailsData.founder || '', // 新建人(后端用)
            ...this.formParams
          },
          list: arrs
        }
    
        const {code, message}: any = await this.services.updateExwarehousData(params, 0);
        if (code === 0) {
          this.msg.success('拆单成功');
          this.setOfCheckedId.clear();
          this.loadDetailData();
        } else {
          this.msg.error(message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * other
   * ----------------------------------------------------------------
   */

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    const calcArrs = this.exwarehousTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  coprText(str: any) {
    this.commonService.copyStr(str);
  }

  downFile(item: any) {
    this.commonService.downLoadUrlFile(item.url);
  }

  pageBack() {
    history.back();
  }

  handleList(arrs: Array<string>) {
    let newArr: Array<any> = [];
    if (arrs) {
      newArr = arrs.map(m => {
        let nArr = m.split('/');
        return {
          name: nArr[nArr.length - 1],
          url: m
        }
      })
    }

    return newArr;
  }
}
